<script setup>
import {ref, onMounted, nextTick} from 'vue'
import VideoApi from "@/apis/VideoApi.js";
import echarts from "@/utils/Echarts/echarts.js";
import dayjs from "dayjs";
import HorizonVideoCard from "@/components/horizonVideoCard/horizonVideoCard.vue";
import {useRouter} from "vue-router";
import User from "@/utils/User/User.js";

const router = useRouter()

const videostatistics = ref([
  {
    name: '粉丝数',
    valueNum: 0,
    icon: '<i class="iconfont icon-dongtaiweixuanzhong"></i>'
  },
  {
    name: '视频数',
    valueNum: 0,
    icon: '<i class="iconfont icon-UPzhu"></i>'
  },
  {
    name: '播放',
    valueNum: 0,
    icon: '<i class="iconfont icon-bofangshu"></i>'
  },
  {
    name: '弹幕',
    valueNum: 0,
    icon: '<i class="iconfont icon-danmushu"></i>'
  },
  {
    name: '收藏',
    valueNum: 0,
    icon: '<i class="iconfont icon-shoucang"></i>'
  },
  {
    name: '点赞',
    valueNum: 0,
    icon: '<i class="iconfont icon-zan"></i>',
  },
  {
    name: '评论',
    valueNum: 0,
    icon: '<i class="iconfont icon-_ico_reply"></i>'
  },

]);
const carouselItems = ref([
  {
    ImgUrl:'/上海大学2025.jpg',
    Title:'上海大学2025',
    aUrl:"https://lib.shu.edu.cn/",
  },
  {
    ImgUrl:"https://lib.shu.edu.cn/images/lunxian_20241011_0.jpg",
    Title:'上海大学图书馆',
    aUrl:"https://lib.shu.edu.cn/",
  },
  {
    ImgUrl:"https://bkzsw.shu.edu.cn/images/baokaozhinan.jpg",
    Title:'',
    aUrl:"https://bkzsw.shu.edu.cn/",
  },
])
const videoChart = ref(null);
const videos = ref([]);
const userInfo = ref(null);

const initChart = () => {
  const tableData = videos.value;
  const newOption = {
    grid: {
      left: '5%',
      right: '0%',
      // top: '10%',  // 可以根据需要调整顶部间距
      // bottom: '10%' // 可以根据需要调整底部间距
    },
    title: {
      text: '视频点赞趋势'
    },
    // legend: {
    //   data: ['响应时间', '处理时间', '总时间']
    // },
    tooltip: {
      backgroundColor: '#fff',
      textStyle: {
        color: '#333',
      },
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter:  (params) => {
        // 找到当前 x 轴值对应的事件description
        const currentIndex = params[0].dataIndex;
        if (currentIndex >= 0 && tableData[currentIndex]) {
          const videoInfo = tableData[currentIndex];
          return `
                  点赞数: ${videoInfo.like_count}<br>
                  收藏数: ${videoInfo.favorite_count}<br>
                  视频id: ${videoInfo.fvid}<br>
                `;
        }
        return '';
      }
    },
    xAxis: {
      type: 'category',
      data: tableData.map(item=>{
        const date = dayjs(item.upload_time);
        return date.format('MM-DD HH:mm')
      })
    },
    yAxis: {
      type: 'value',
      name: '点赞',
      minInterval: 1,
    },
    series: [
      {
        name: '视频点赞',
        type: 'line',
        connectNulls:true,
        data: tableData.map((item)=> ({
          value: item.like_count,
          // silent: item.responseDuration === null || item.responseDuration === 0 ,
        })),
        smooth: false,
        symbol: 'none',
        itemStyle: {
          color: '#5470C6'
        },
        lineStyle: {
          color: 'rgb(255,102,153)', // 设置线条颜色
          width: 2 // 可选：设置线条宽度
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgb(255,102,153,0.3)' // 起点颜色（顶部）
              },
              {
                offset: 1,
                color: 'rgb(255,102,153,0)' // 终点颜色（底部）
              }
            ],
            global: false // 默认为 false
          }
        },
      },
    ]
  };
  const chart = echarts.init(document.getElementById('video-chart'));
  // 更新图表配置
  chart.setOption(newOption);
  videoChart.value = chart;
  // 调整大小以确保正确渲染
  nextTick(() => {
    chart.resize();
  });
}

//获取首页视频
async function fetchVideos() {
  try {
    const res = await VideoApi.fetchAllVideo(30,1);
    videos.value = res.data.videos;
    console.log('视频',res.data)
  } catch (error) {
    console.error('Failed to fetch videos:', error)
  }
}
const goExternalLink = (link) => {
  window.location.href= link;
}

// 获取用户视频
const fetchUserVideos = async () => {
  const res = await VideoApi.fetchUserVideo();
  videos.value = res.data.videos;
}

const fetchUserInfo = async () => {
  const res = await User.getUserInfo();
  userInfo.value = res;
}

// 更新统计数据的方法
const updateStatistics = () => {
  const videoArray = videos.value;

  if (videoArray.length === 0) {
    console.log('No videos available to calculate statistics.');
    return;
  }

  // 初始化统计数据
  let totalViewCount = 0;
  let totalCommentCount = 0;
  let totalFavoriteCount = 0;
  let totalLikeCount = 0;

  // 遍历所有视频数据，累加各个统计数据
  videoArray.forEach(video => {
    totalViewCount += video.view_count || 0;
    totalCommentCount += video.comment_count || 0;
    totalFavoriteCount += video.favorite_count || 0;
    totalLikeCount += video.like_count || 0;
  });

  // 计算平均值
  const averageViewCount = totalViewCount / videoArray.length;
  const averageCommentCount = totalCommentCount / videoArray.length;
  const averageFavoriteCount = totalFavoriteCount / videoArray.length;
  const averageLikeCount = totalLikeCount / videoArray.length;

  // 更新 videostatistics
  videostatistics.value = [
    {
      name: '粉丝数',
      valueNum: userInfo.value.fans_num, // 粉丝数在你的数据结构中没有直接对应字段，这里保持为0
      icon: '<i class="iconfont icon-dongtaiweixuanzhong"></i>'
    },
    {
      name: '视频数',
      valueNum: videoArray.length,
      icon: '<i class="iconfont icon-UPzhu"></i>'
    },
    {
      name: '播放',
      valueNum: averageViewCount,
      icon: '<i class="iconfont icon-bofangshu"></i>'
    },
    {
      name: '弹幕',
      valueNum: 0,
      icon: '<i class="iconfont icon-danmushu"></i>'
    },
    {
      name: '收藏',
      valueNum: averageFavoriteCount,
      icon: '<i class="iconfont icon-shoucang"></i>'
    },
    {
      name: '点赞',
      valueNum: averageLikeCount,
      icon: '<i class="iconfont icon-zan"></i>',
    },
    {
      name: '评论',
      valueNum: averageCommentCount,
      icon: '<i class="iconfont icon-_ico_reply"></i>'
    },
  ];
};

onMounted(async ()=>{
  await fetchVideos();
  await fetchUserVideos();
  await fetchUserInfo();
  updateStatistics();
  initChart();
  window.addEventListener('resize', () => {
    nextTick(()=>{
      videoChart.value.resize();
    })
  });
})

</script>

<template>
<div class="PlatFormHome-main">
  <div class="PlatFormHome-card carousel-card">
    <el-carousel class="carousel-box" height="100%">
      <el-carousel-item class="carousel-item" v-for="item in carouselItems" :key="item"
       @click="goExternalLink(item.aUrl)"
      >
        <img :src="item.ImgUrl" alt="">
        <h3 class="carousel-item-h3">{{ item.Title }}</h3>
      </el-carousel-item>
    </el-carousel>
    <div class="hot-topic-box">
      <div class="hot-topic-box-title">
        热门话题
      </div>
      <div class="hot-topic-box-content">
        <div class="hot-topic-box-content-item">
          <a href="https://www.shu.edu.cn/info/1053/366615.htm">再登Cell！上海大学医学院卞月珉教授作为共同作者发表最新研究成果</a>
        </div>
        <div class="hot-topic-box-content-item">
          <a href="https://www.shu.edu.cn/bydldb.htm">上海大学2024毕业典礼回放</a>
        </div>
        <div class="hot-topic-box-content-item">
          <a href="https://www.shu.edu.cn/info/1051/366425.htm">学期制优化改革意见建议征集反馈汇总</a>
        </div>
      </div>
    </div>
  </div>
  <div class="PlatFormHome-card video-statistics-card">
    <div class="video-statistics-card-title">
      核心数据预览
    </div>
    <div class="video-statistics-card-content">
      <div v-for="item in videostatistics" class="video-statistics-card-content-item">
        <div class="statistics-item-name">
          <!-- 如果是组件则直接渲染 -->
          <component :is="item.icon" v-if="typeof item.icon === 'object'" />
          <!-- 如果是HTML字符串则使用v-html -->
          <span v-html="item.icon" v-else></span>
          {{item.name}}
        </div>
        <div class="statistics-item-value">
          {{item.valueNum}}
        </div>
      </div>
    </div>
    <div ref="videoChart" class="statistic-echarts-card-chart" id="video-chart"></div>
  </div>

<!--  <div class="PlatFormHome-card statistic-echarts-card">-->
<!--    <div class="statistic-echarts-card-title">-->
<!--      数据统计-->
<!--    </div>-->
<!--     <div ref="videoChart" class="statistic-echarts-card-chart" id="video-chart"></div>-->
<!--  </div>-->

</div>
</template>

<style scoped lang="less">
.PlatFormHome-main{
  margin-top: 20px;
  width: 80%;
  min-height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-direction: column;
  .PlatFormHome-card{
    width: 100%;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    border-radius: 15px;
  }

  .carousel-card{
    flex: 0 0 240px;
    margin-bottom: 30px;
    background-color: transparent;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: row;

    .carousel-box{
      height: 100%;
      flex: 1;
      margin-right: 20px;
      .carousel-item-h3{
        position: absolute;
        bottom: 25px;
        left: 15px;
        color: white;
        font-size: 25px;
      }
      img{
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .hot-topic-box{
      background-color: #fff;
      flex: 0 0 300px;
      width: 300px;
      height: 100%;
      padding: 10px;
      .hot-topic-box-title{
        font-size: 16px;
      }
      &-content{
        padding-left: 10px;
        width: 100%;
        &-item{
          margin: 15px 0;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          a{
            text-decoration: none;
            color: #333;
            transition: color 0.3s ease;
          }
        }
      }
    }
  }

  .video-statistics-card{
    //height: 900px;
    margin-bottom: 30px;

    &-title{
      width: 100%;
      height: 30px;
      padding: 0 20px;
      text-align: start;
      margin: 20px 0;
      font-size: 18px;
      font-weight: 600;
    }

    &-content{
      width: 100%;
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      padding: 0 20px;
      gap: 20px;

      &-item{
        //cursor: pointer;
        height: 80px;
        background-color: rgba(0, 174, 236, .04);
        padding: 8px 15px;
        border-radius: 15px;

        .statistics-item-name{
          font-size: 14px;
          color: rgba(0, 0, 0, .5);
        }
        .statistics-item-value{
          color: #00aeec;
          font-size: 22px;
        }
      }
    }
    .statistic-echarts-card-chart{
      width: calc(100% - 40px);
      margin: 20px 0;
      height: 300px;
      padding: 20px;
    }
  }

  .statistic-echarts-card{
    height: 400px;

    &-title{
      width: 100%;
      height: 30px;
      padding: 0 20px;
      text-align: start;
      margin: 20px 0;
    }
    &-chart{
      width: 90%;
      height: 270px;
      border: 1px rgba(0,0,0,0.1) solid;
      border-radius: 15px;
    }
  }
}
</style>
